//
//  TopViewController.m
//  Baker
//
//  Created by b z on 12-4-18.
//  Copyright (c) 2012年 wsfk. All rights reserved.
//

#import "TopViewController.h"

#import "BookViewController.h"
#import "InterceptorWindow.h"

@implementation TopViewController

@synthesize myWebView;

- (id)initWithBookViewDelegate:(UIViewController *)delegate
{
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        //初始化宽和高为零
        topWidth = 0;
        topHeight = 0;
        bookView =(BookViewController *)delegate;
        
        [self setTopViewHidden:YES withAnimation:NO];
        [self.view setBackgroundColor:[UIColor clearColor]];
        [self setPageSizeForOrientation:[self interfaceOrientation]];
    }
    return self;
}
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad{
    [super viewDidLoad];
}

- (void)viewDidUnload
{
    [myWebView release];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated{
    [self loadTopViewWithTopWidth:topWidth topHeight:topHeight];
}

#pragma webViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSRange range1 = [request.URL.relativeString rangeOfString:@"#?param=goback"];
    
    if (range1.length>0) {
        //返回书架
        [self goBackHome];
    }
    
    return YES;
}

- (void)setTopViewHidden:(BOOL)hidden withAnimation:(BOOL)animation{
    CGRect myFrame;
    CGRect topWebFrame;
    if (hidden) {
        myFrame = CGRectMake(0, 0, 0, 0);
        topWebFrame = CGRectMake(0, 0, 0, 0);
    }else{
        myFrame =CGRectMake(0,20, topWidth, topHeight);
        topWebFrame = CGRectMake(0,-7, topWidth,topHeight);
    }
    if (animation) {
        [UIView beginAnimations:@"slideTopView" context:nil]; {
            [UIView setAnimationDuration:0.3];//设置出现的时间
            
            [self setTopViewFrame:myFrame];
            [myWebView setFrame:topWebFrame];
        }
        [UIView commitAnimations];//提交动画
    } else {
        [self setTopViewFrame:myFrame];
        [myWebView setFrame:topWebFrame];
    }
    [self.view setHidden:hidden];
}
- (void)hiddenTopView{
    [self setTopViewHidden:YES withAnimation:NO];
}

- (void)setPageSizeForOrientation:(UIInterfaceOrientation)orientation {
	CGRect screenBounds = [[UIScreen mainScreen] bounds];
    
	if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
		topWidth = screenBounds.size.height;
		topHeight = 75;
    } else {
        topWidth = screenBounds.size.width;
		topHeight = 75;
	}
    
}

- (void)willRotate {
    [self fadeOut];
}

- (void)fadeIn {
    [UIView beginAnimations:@"fadeInTopView" context:nil]; {
        [UIView setAnimationDuration:0.2];
        
        self.view.alpha = 1.0;
    }
    [UIView commitAnimations];
}

- (void)fadeOut {
    [UIView beginAnimations:@"fadeOutTopView" context:nil]; {
        [UIView setAnimationDuration:0.0];
        
        self.view.alpha = 0.0;
    }
    [UIView commitAnimations];
}

- (void)rotateFromOrientation:(UIInterfaceOrientation)fromInterfaceOrientation toOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    BOOL hidden = [self isHidden]; // cache hidden status before setting page size
    
    [self setPageSizeForOrientation:toInterfaceOrientation];
    [self setTopViewHidden:hidden withAnimation:NO];   
    [self fadeIn];
}

- (void)setTopViewFrame:(CGRect)frame{
    self.view.frame = frame;
}

- (BOOL)isHidden{
    return [UIApplication sharedApplication].statusBarHidden;
}
- (void)goBackHome {
    
    [self saveLastPageReference];
    NSArray * windows =[UIApplication sharedApplication].windows;
    for (UIWindow *window in windows) {
        if ([window isKindOfClass:[InterceptorWindow class]]) {
            [(InterceptorWindow *)window setDisableTap:YES];
        }
    }
    // Check if iOS5 method is supported
    if ([bookView respondsToSelector:@selector(dismissViewControllerAnimated:completion:)]) {
        // iOS 5
        [bookView dismissViewControllerAnimated:YES completion:nil];
    } else {
        // iOS 4
        [bookView dismissModalViewControllerAnimated:YES];
    }
    
}


//保存当前看过的也面
- (void)saveLastPageReference {
	
//	NSUserDefaults *userDefs = [NSUserDefaults standardUserDefaults];
//	
//    NSMutableDictionary *bookInfo = [[NSMutableDictionary alloc]init];
//	// Save last page viewed reference
//	if (bookView.currentPageNumber > 0) {
//		NSString *lastPageViewed = [NSString stringWithFormat:@"%d", bookView.currentPageNumber];
//        [bookInfo setObject:lastPageViewed forKey:@"lastPageViewed"];
//        
//	}
//	
//	// Save last scroll index reference
//	if (bookView.currPage != nil) {
//		NSString *lastScrollIndex = [bookView.currPage stringByEvaluatingJavaScriptFromString:@"window.scrollY;"];
//        [bookInfo setObject:lastScrollIndex forKey:@"lastScrollIndex"];
//	}
//    [userDefs setObject:bookInfo forKey:[bookView getBookName]];
//    [bookInfo release];
}

- (void)loadTopViewWithTopWidth:(int)width topHeight:(int)height{
    [myWebView setFrame:CGRectMake(0, 0, topWidth, topHeight)];
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"books" ofType:nil];
    NSString *path = [bundlePath stringByAppendingPathComponent:@"top.html"];
    
    NSURL *url = [[[NSBundle mainBundle]resourceURL] URLByAppendingPathComponent:@"books"];
    
    NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:path];
    NSString *htmlString = [[NSString alloc] initWithData:[readHandle readDataToEndOfFile] encoding:NSUTF8StringEncoding];
    
    myWebView.opaque = NO;
    myWebView.backgroundColor = [UIColor clearColor];
    myWebView.delegate = self;
    [myWebView.scrollView setScrollEnabled:NO];
    [myWebView loadHTMLString:htmlString baseURL:url];
    [self.view addSubview:myWebView];
    [htmlString release];
}
@end
